package edu.iscas.appcheckclient.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.github.promeg.pinyinhelper.Pinyin;

import org.json.JSONArray;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import edu.iscas.appcheckclient.Adpater.MyAdapter;
import edu.iscas.appcheckclient.BuildConfig;
import edu.iscas.appcheckclient.R;
import edu.iscas.appcheckclient.model.AppInfo;
import edu.iscas.appcheckclient.service.AppInfoProvider;
import edu.iscas.appcheckclient.service.RecordService;
import edu.iscas.appcheckclient.service.network.HttpUtil;
import edu.iscas.appcheckclient.widget.IndexableListView;

public class AppListActivity extends AppCompatActivity {
    private static final String TAG = AppListActivity.class.getSimpleName();
    private IndexableListView appListView;//应用信息列表
    private AppInfoProvider appInfoProvider;
    private AppManagerAdapter adapter;
    private List<AppInfo> appList;
    private PopupWindow window;

    private boolean isRecordServiceCreated(){
        return RecordService.getRecordService() != null;
    }

    @Override
    protected void onResume() {
        super.onResume();

        appInfoProvider = new AppInfoProvider(AppListActivity.this);
        appList = appInfoProvider.getAllApps();

        appListView = (IndexableListView)findViewById(R.id.lv_app_list);
        adapter = new AppManagerAdapter(appList);
        appListView.setAdapter(adapter);
        appListView.setFastScrollEnabled(true);

        appListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    //如果没有打开辅助功能，提示并直接返回
                    if (!isRecordServiceCreated()) {
                        Toast.makeText(AppListActivity.this, "Should start Accessibility Service first!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    AppInfo info = (AppInfo) appListView.getItemAtPosition(position);
                    PackageInfo packageInfo = getPackageManager().getPackageInfo(info.getPackageName(), PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_ACTIVITIES);

                    Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);

                    resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);

                    resolveIntent.setPackage(packageInfo.packageName);

                    //寻找主启动acitivity
                    List<ResolveInfo> activities = getPackageManager().queryIntentActivities(resolveIntent, 0);

                    //有些应用是无法启动的，所以我们就要判断一下
                    if (activities != null && activities.size() > 0) {
                        ResolveInfo ri = activities.iterator().next();
                        ActivityInfo startActivityInfo = ri.activityInfo;
                        //在扫描出来的应用里面，第一个是具有启动意义的
                        //ActivityInfo startActivity = activityInfos[0];
                        //设置Intent，启动activity
                        try {
                            Intent intent = new Intent(Intent.ACTION_MAIN);
                            intent.addCategory(Intent.CATEGORY_LAUNCHER);

                            //注意这里，api里面写的是如果不在activity的context里面执行startActivity()必须将flag设为这个值
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            ComponentName cn = new ComponentName(startActivityInfo.packageName, startActivityInfo.name);
                            intent.setComponent(cn);
                            //调用被测应用的activity
                            startActivity(intent);
                            //开始录制
                            RecordService.startRecording(info);

                            Toast.makeText(AppListActivity.this, "start recording", Toast.LENGTH_SHORT).show();

                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(AppListActivity.this, "start failed", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(AppListActivity.this, "this app can't be started", Toast.LENGTH_SHORT).show();
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    Toast.makeText(AppListActivity.this, "Package name not found", Toast.LENGTH_SHORT).show();
                }
            }
        });
        getTestAPK();
    }

    @Override
    protected void onPause() {
        super.onPause();
        appList.clear();
        appListView = null;
        adapter = null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_list);

//        ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
//        int heapSize = manager.getMemoryClass();
//        Log.d("heapSize", String.valueOf(heapSize));

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
                startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
            }
        });
    }

    private void getTestAPK() {
        HttpUtil httpUtil = HttpUtil.getInstance(AppListActivity.this,"http://" + BuildConfig.IP + ":" + BuildConfig.PORT);
        httpUtil.jsonArrayRequest(Request.Method.GET, AppListActivity.this.getResources().getString(R.string.upload_apk),
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArray) {
                        Log.d("TAG", jsonArray.toString());
                        popAwindow(AppListActivity.this.getWindow().getDecorView(), jsonArray);
                    }
                }

                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
                //Toast.makeText(AppListActivity.this, error.getMessage().toString(),Toast.LENGTH_LONG).show();
            }
        });
        /*
        Log.e("TAG", response.toString());
                Toast.makeText(AppListActivity.this, response.toString(),Toast.LENGTH_LONG).show();
         */

    }



    private void popAwindow(View parent, JSONArray jsonArray) {
        ListView list;
        if (window == null) {
            LayoutInflater lay = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = lay.inflate(R.layout.popupwindow, null);
            v.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
            //初始化listview，加载数据。
            list=(ListView)v.findViewById(R.id.lv);
            MyAdapter adapter=new MyAdapter(AppListActivity.this);
            Log.d(TAG, jsonArray.toString());
            adapter.setMDate(jsonArray);
            list.setAdapter(adapter);
            list.setItemsCanFocus(false);
            list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            list.setOnItemClickListener(listClickListener);

            window = new PopupWindow(v, 550,560);
        }

        //设置整个popupwindow的样式。
        window.setBackgroundDrawable(getResources().getDrawable(R.drawable.rounded_corners_pop));
        //使窗口里面的空间显示其相应的效果，比较点击button时背景颜色改变。
        //如果为false点击相关的空间表面上没有反应，但事件是可以监听到的。
        //listview的话就没有了作用。
        window.setFocusable(true);//如果不设置setFocusable为true，popupwindow里面是获取不到焦点的，那么如果popupwindow里面有输入框等的话就无法输入。
        window.update();
        window.showAtLocation(parent, Gravity.CENTER_VERTICAL, 0, 0);
    }

    AdapterView.OnItemClickListener listClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
//            RecyclerView.ViewHolder vHollder = (RecyclerView.ViewHolder) view.getTag();
//            // 在每次获取点击的item时将对于的checkbox状态改变，同时修改map的值。
//            vHollder.cBox.toggle();
//            MyAdapter.isSelected.put(position, vHollder.cBox.isChecked());
        }
    };

    private void closeWindow(){
        //提交数据时关闭popupwindow。
        if (window != null) {
            window.dismiss();
        }
    }












    private class AppManagerAdapter extends BaseAdapter implements SectionIndexer {

        private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        private int[] sectionsPosition;

        private List<AppInfo> appList;

        public AppManagerAdapter(List<AppInfo> appList) {
            this.appList = appList;
            Collections.sort(this.appList, new Comparator<AppInfo> (){
                @Override
                public int compare(AppInfo leftAppInfo, AppInfo rightAppInfo) {
                    //if left < right return negative
                    char firstLeft = leftAppInfo.getAppName().charAt(0);
                    char firstRight = rightAppInfo.getAppName().charAt(0);

                    String leftPinYin = Pinyin.toPinyin(firstLeft);
                    leftAppInfo.setFirstCharacter(leftPinYin.charAt(0));

                    String rightPinYin = Pinyin.toPinyin(firstRight);
                    rightAppInfo.setFirstCharacter(rightPinYin.charAt(0));

                    return leftPinYin.compareTo(rightPinYin);
                }
            });
            this.sectionsPosition = new int[mSections.length()];
            int indexOfSection = 0;
            for(int i = 0; i < appList.size(); i++){
                AppInfo appInfo = appList.get(i);
//                Log.d("onCreate", "appInfo.getFirstCharacter():" +
//                        appInfo.getFirstCharacter() + " mSections.charAt(indexOfSection):" + mSections.charAt(indexOfSection) +
//                        " AppName:" + appInfo.getAppName());
                if(!Character.isLetter(appInfo.getFirstCharacter())) {
                    continue;
                }
                if(appInfo.getFirstCharacter() != mSections.charAt(indexOfSection)){
                    do{
                        indexOfSection++;
                        sectionsPosition[indexOfSection] = i;
                    }while(appInfo.getFirstCharacter() != mSections.charAt(indexOfSection));
                    if(indexOfSection == mSections.length() - 1)
                        break;
                }
            }
        }

        @Override
        public int getPositionForSection(int sectionIndex) {
            //Log.d("getPositionForSection", "name:" + appList.get(sectionsPosition[sectionIndex]).getAppName());
            return sectionsPosition[sectionIndex];
        }


        @Override
        public Object[] getSections() {
            String[] sections = new String[mSections.length()];
            for (int i = 0; i < mSections.length(); i++)
                sections[i] = String.valueOf(mSections.charAt(i));
            return sections;
        }

        @Override
        public int getSectionForPosition(int position) {
            return 0;
        }

        public int getCount() {
            return appList.size();
        }

        @Override
        public Object getItem(int position) {
            return appList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            AppInfo info = appList.get(position);
            AppListViews views;
            if(convertView == null) {
                View view = View.inflate(AppListActivity.this, R.layout.app_list_item, null);
                convertView = view;
                views = new AppListViews();
                views.appIconView = (ImageView) view.findViewById(R.id.iv_app_list_icon);
                views.appNameView = (TextView) view.findViewById(R.id.tv_app_list_name);
            }
            else {
                views = (AppListViews) convertView.getTag();
            }
            views.appIconView.setImageDrawable(info.getIcon());
            views.appNameView.setText(info.getAppName());
            convertView.setTag(views);
            return convertView;
        }

    }
    /**
     * 用来优化listview的类
     * */
    private class AppListViews {
        ImageView appIconView;
        TextView appNameView;
    }

}
